package com.zf.shuashua.advert;

import android.app.Activity;
import android.text.TextUtils;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdManager;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.bytedance.sdk.openadsdk.TTFullScreenVideoAd;
import com.vise.xsnow.http.callback.ACallback;
import com.zf.shuashua.AdvertUtils;
import com.zf.shuashua.ShuaApplication;
import com.zf.shuashua.bean.AdvertReport;
import com.zf.shuashua.bean.BaseData;
import com.zf.shuashua.manager.ActionThirdReportManager;
import com.zf.shuashua.ui.mine.LogUtil;
import com.zf.shuashua.utils.ToastUtil;
import com.zf.shuashua.utils.Util;

import java.lang.ref.WeakReference;

/**
 * 穿山甲全屏视频
 */
public class FullAdvertByteManager {

    private TTAdNative mTTAdNative;
    private TTFullScreenVideoAd mttRewardVideoAd;
    private String mAdvertType = AdvertConstants.REWARD_TYPE_TASK;
    private String mCodeId = "945333161";
    private String mReportID = "";

    private static FullAdvertByteManager instance;
    private WeakReference<Activity> weakReference;

    private FullAdvertByteManager() {
    }

    public static FullAdvertByteManager getInstance() {
        if (null == instance) {
            synchronized (FullAdvertByteManager.class) {
                if (null == instance) {
                    instance = new FullAdvertByteManager();
                }
            }
        }
        return instance;
    }

    public void showAdvert(Activity activity, String advertType, String reportId, OnRewardListener listener) {
        this.weakReference = new WeakReference<>(activity);
        this.mAdvertType = advertType;
        this.mReportID = reportId;

        isComplete = false;
        mCodeId = getCodeId();

        showByteAdvert(activity, listener);
    }

    public void showAdvert(Activity activity, String advertType, String reportId, String codeId, OnRewardListener listener) {
        this.weakReference = new WeakReference<>(activity);
        this.mAdvertType = advertType;
        this.mReportID = reportId;

        isComplete = false;
        mCodeId = codeId;
        showByteAdvert(activity, listener);
    }

    /**
     * 穿山甲广告
     *
     * @param activity
     * @param listener
     */
    private void showByteAdvert(Activity activity, OnRewardListener listener) {
        if (mTTAdNative == null) {
            setupSDK(activity);
        }
        loadAd(listener);
    }

    private void setupSDK(Activity activity) {
        //step1:初始化sdk
        TTAdManager ttAdManager = TTAdManagerHolder.get();
        //step2:(可选，强烈建议在合适的时机调用):申请部分权限，如read_phone_state,防止获取不了imei时候，下载类广告没有填充的问题。
        TTAdManagerHolder.get().requestPermissionIfNecessary(activity);
        //step3:创建TTAdNative对象,用于调用广告请求接口
        mTTAdNative = ttAdManager.createAdNative(ShuaApplication.getContext());
    }

    private void showAdvert() {
        if (mttRewardVideoAd != null) {
            //step6:在获取到广告后展示,强烈建议在onRewardVideoCached回调后，展示广告，提升播放体验
            //该方法直接展示广告
            mttRewardVideoAd.showFullScreenVideoAd(weakReference.get());
            //展示广告，并传入广告展示的场景
            //mttRewardVideoAd.showRewardVideoAd(this, TTAdConstant.RitScenes.CUSTOMIZE_SCENES, "scenes_test");
            mttRewardVideoAd = null;
        }
        reportRequestSucc(1);
    }

    private void dealClose(String planId, OnRewardListener listener){
        if(!isComplete){
            return;
        }
        AdReportManager.getInstance().reportAdvertAction(uuiThirdAdvert, planId, AdvertReport.EventType.VideoEnd, getReportType(), "1", new ACallback<BaseData>() {
            @Override
            public void onSuccess(BaseData data) {
                if (data != null && data.isStatus()) {
                    weakReference.get().runOnUiThread(() -> {
                        if (listener != null) {
                            listener.onAdClose();
                        }
                    });
                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {

            }
        });
    }

    private void reportRequestStart(){
        ActionThirdReportManager.getInstance().reportRequestStart(1, 5, mCodeId, 1);
    }

    private void reportRequestSucc(int return_num) {
        ActionThirdReportManager.getInstance().reportRequestSucc(1, 5, mCodeId, return_num);
    }

    private void reportRequestFail(String error_code, String error_msg){
        ActionThirdReportManager.getInstance().reportRequestFail(1, 5, mCodeId, 1, error_code, error_msg);
    }

    private void reportRequestRend(String error_code, String error_msg){
        ActionThirdReportManager.getInstance().reportRequestRend(1, 5, mCodeId, error_code, error_msg);
    }

    private boolean mHasShowDownloadActive = false;

    private String uuiThirdAdvert;

    private boolean isComplete = false;

    private void loadAd(OnRewardListener listener) {
        if(TextUtils.isEmpty(mCodeId)){
            mCodeId = "945333161";
        }
        uuiThirdAdvert = Util.getUUID32();
        //step4:创建广告请求参数AdSlot,具体参数含义参考文档
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(mCodeId)
                .setSupportDeepLink(true)
                //模板广告需要设置期望个性化模板广告的大小,单位dp,激励视频场景，只要设置的值大于0即可
                .setExpressViewAcceptedSize(500, 500)
                .setOrientation(TTAdConstant.VERTICAL) //必填参数，期望视频的播放方向：TTAdConstant.HORIZONTAL 或 TTAdConstant.VERTICAL
                .build();
        //step5:请求广告
        mTTAdNative.loadFullScreenVideoAd(adSlot, new TTAdNative.FullScreenVideoAdListener() {
            @Override
            public void onError(int code, String message) {
//                LogUtil.d("onError: " + code + ", " + message);
//                rewardedAdvertResult("false");
                weakReference.get().runOnUiThread(() -> {
                    if (listener != null) {
                        listener.onVideoError();
                    }
                });
                reportRequestFail(code + "", message);
            }

            //视频广告加载后，视频资源缓存到本地的回调，在此回调后，播放本地视频，流畅不阻塞。
            @Override
            public void onFullScreenVideoCached() {
//                showAdvert();
            }

            //视频广告的素材加载完毕，比如视频url等，在此回调后，可以播放在线视频，网络不好可能出现加载缓冲，影响体验。
            @Override
            public void onFullScreenVideoAdLoad(TTFullScreenVideoAd ad) {
                LogUtil.d("onRewardVideoAdLoad");

                mttRewardVideoAd = ad;
                String planId = System.identityHashCode(ad) + "";
                mttRewardVideoAd.setFullScreenVideoAdInteractionListener(new TTFullScreenVideoAd.FullScreenVideoAdInteractionListener() {
                    @Override
                    public void onAdShow() {
                        AdReportManager.getInstance().reportAdvertAction(uuiThirdAdvert, planId, AdvertReport.EventType.VideoStart, getReportType());
                    }

                    @Override
                    public void onAdVideoBarClick() {
                        if (listener != null) {
                            listener.onAdClick();
                        }
                        AdReportManager.getInstance().reportAdvertAction(uuiThirdAdvert, planId, AdvertReport.EventType.VideoClick, getReportType());
                    }

                    @Override
                    public void onAdClose() {
                        dealClose(planId, listener);
                    }

                    @Override
                    public void onVideoComplete() {
                        isComplete = true;
                        if (listener != null) {
                            listener.onVideoComplete();
                        }
//                        AdReportManager.getInstance().reportAdvertAction(uuiThirdAdvert, planId, AdvertReport.EventType.VideoEnd, getReportType());
                    }

                    @Override
                    public void onSkippedVideo() {
                        ToastUtil.showToast(weakReference.get(), "观看完整视频才能获得奖励哦");
                    }
                });

                mttRewardVideoAd.setDownloadListener(new TTAppDownloadListener() {
                    @Override
                    public void onIdle() {
                        mHasShowDownloadActive = false;
                    }

                    @Override
                    public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {
//                        LogUtil.d("onDownloadActive==totalBytes=" + totalBytes + ",currBytes=" + currBytes + ",fileName=" + fileName + ",appName=" + appName);

                        if (!mHasShowDownloadActive) {
                            mHasShowDownloadActive = true;
//                            TToast.show(RewardVideoActivity.this, "下载中，点击下载区域暂停", Toast.LENGTH_LONG);
                        }
                    }

                    @Override
                    public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {
//                        LogUtil.d("onDownloadPaused===totalBytes=" + totalBytes + ",currBytes=" + currBytes + ",fileName=" + fileName + ",appName=" + appName);
//                        TToast.show(RewardVideoActivity.this, "下载暂停，点击下载区域继续", Toast.LENGTH_LONG);
                    }

                    @Override
                    public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {
//                        LogUtil.d("onDownloadFailed==totalBytes=" + totalBytes + ",currBytes=" + currBytes + ",fileName=" + fileName + ",appName=" + appName);
//                        TToast.show(RewardVideoActivity.this, "下载失败，点击下载区域重新下载", Toast.LENGTH_LONG);
                    }

                    @Override
                    public void onDownloadFinished(long totalBytes, String fileName, String appName) {
//                        LogUtil.d("onDownloadFinished==totalBytes=" + totalBytes + ",fileName=" + fileName + ",appName=" + appName);
//                        TToast.show(RewardVideoActivity.this, "下载完成，点击下载区域重新下载", Toast.LENGTH_LONG);
                    }

                    @Override
                    public void onInstalled(String fileName, String appName) {
//                        LogUtil.d("onInstalled==" + ",fileName=" + fileName + ",appName=" + appName);
//                        TToast.show(RewardVideoActivity.this, "安装完成，点击下载区域打开", Toast.LENGTH_LONG);
                    }
                });

                weakReference.get().runOnUiThread(() -> showAdvert());
            }
        });

        reportRequestStart();
    }

    private String getReportType() {
        return AdvertUtils.getReportType(mAdvertType, mReportID);
    }

    private String getCodeId() {
        if(!TextUtils.isEmpty(mAdvertType) && mAdvertType.equals(AdvertConstants.REWARD_TYPE_BUBBLE)){
            return "945333161";
        }
        return "945200584";
    }

}
